package com.aica.handler;


import com.aica.bo.UserMessageBo;
import com.aica.bo.response.LoginBo;
import com.aica.constant.RedisTimeConstant;
import com.aica.constant.StringBuilderConstant;
import com.aica.service.UserService;
import com.aica.util.JwtTokenUtil;
import com.aica.util.RedisUtil;
import com.aica.vo.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;



/**
 * 登录成功的处理类
 * @author by
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {

    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType("text/json;charset=utf-8");

        User user = (User) authentication.getPrincipal();

        //更新内存内的用户信息
        UserMessageBo userMessage = userService.refreshUserMessageOnRedis(user.getUsername());

        //存储用户名与ID关系进入redis
        String userIdKey = StringBuilderConstant.USER_ID_ + user.getUsername();
        if (!redisUtil.hasKey(userIdKey)) {
            redisUtil.set(
                    userIdKey,
                    //生成token
                    userMessage.getUserId(),
                    //15天的时效
                    RedisTimeConstant.USER_MESSAGE_TIME_OUT
            );
        }
        //存储用户token进入redis
        String userTokenKey = StringBuilderConstant.USER_TOKEN_ + user.getUsername();
        if (!redisUtil.hasKey(userTokenKey)) {
            redisUtil.set(
                    userTokenKey,
                    //生成token
                    JwtTokenUtil.getToken(
                            userMessage.getUsername(),
                            userMessage.getRoleIds()
                    ),
                    //15天的时效
                    RedisTimeConstant.TOKEN_TIME_OUT
            );
        }
        //token时效小于3天，自动调整为15天重新计时
        if(redisUtil.getExpire(userTokenKey)<=RedisTimeConstant.TOKEN_MIN_TIME_OUT){
            redisUtil.expire(userTokenKey,RedisTimeConstant.TOKEN_TIME_OUT);
        }
        //读取
        String userToken = (String)redisUtil.get(userTokenKey);

        //登录成功返回的信息
        LoginBo loginBo = new LoginBo(
                userMessage,
                //token需要拼接头部"Bearer "
                StringBuilderConstant.TARGET + userToken
        );

        log.info("{}登陆成功",userMessage.getUsername());

        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(new ResultVo<>(loginBo)));


    }
}
